package com.otaku.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.otaku.admin.util.JwtTokenUtil;
import com.otaku.admin.util.ResultEnum;
import com.otaku.admin.util.ResultVO;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * controller 基本类
 * 集成通用方法
 * 1.通用获取用户信息 userName
 * 2.通用返回JSON生成
 */
public class BaseController {

    /**
     * 获取 HttpServletRequest 中保存的token信息
     *
     * @return
     */
    public String getRequestToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authHeader = request.getHeader("Authorization");
        String authToken = null;
        if (authHeader != null) {
            if (authHeader.startsWith("Bearer ")){
                authToken = authHeader.substring("Bearer ".length());
            } else {
                authToken = authHeader;
            }
        }
        return authToken;
    }

    /**
     * 解析token
     *
     * @param authToken
     * @return 用户名
     */
    public String getUserNameFromToken(String authToken) {
        return JwtTokenUtil.parseTokenStr(authToken);
    }

    /**
     * 解析token
     *
     * @return 用户名
     */
    public String getUserNameFromToken() {
        String requestToken = getRequestToken();
        if (StringUtils.isEmpty(requestToken)) {
            return null;
        }
        return JwtTokenUtil.parseTokenStr(requestToken);
    }

    public String responseJSON(Object obj) {
        String s = JSONObject.toJSONString(obj);
        return s;
    }

    /**
     * 返回成功
     *
     * @param object
     * @return
     */
    public String responseSuccessJSON(Object object) {
        return responseJSON(ResultVO.result(ResultEnum.SUCCESS, object, true));
    }

    public String responseSuccessJSON() {
        return responseJSON(ResultVO.result(ResultEnum.SUCCESS, true));
    }

    /**
     * 返回失败
     *
     * @param object
     * @return
     */
    public String responseErrorJSON(Object object) {
        return responseJSON(ResultVO.result(ResultEnum.FAILURE, object, true));
    }
}
